package com.bnuz.vtl.security;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Collection;

@Component
@Slf4j
public class CusUserAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private CusUserDetailsService cusUserDetailsService;

    /**
     * 用户登陆认证逻辑
     *
     * @param authentication 认证
     * @return 认证结果
     */
    @Override
    public Authentication authenticate(Authentication authentication) {
        String username = authentication.getName();
        String unencryptedPassword = (String) authentication.getCredentials();
        UserDetails user = cusUserDetailsService.loadUserByUsername(username);
        if (user == null) {
            log.warn(username + " - 系统用户不存在");
            throw new BadCredentialsException("用户不存在");
        } else {
            if (unencryptedPassword.equals(user.getPassword())) {
                Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
                return new UsernamePasswordAuthenticationToken(user, unencryptedPassword, authorities);
            } else {
                log.warn(username + " - 用户名或密码错误");
                throw new BadCredentialsException("用户名或密码错误");
            }
        }
    }

    @Override
    public boolean supports(Class<?> arg0) {
        return true;
    }
}
